package trading.algo;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import trading.bo.EmailAccessorBO;
import trading.bo.IBAccessorBO;
import trading.util.OrderSplitHelper;

public class STKBuyOrderTask extends TimerTask {

    private int size;
    private String ticker;
    private IBAccessorBO ibAccessorBO;
    private EmailAccessorBO emailAccessorBO;
    private OrderSplitHelper orderSplitHelper;
    private boolean shouldSplit;

    public STKBuyOrderTask(int size, String ticker, IBAccessorBO ibAccessorBO,
            EmailAccessorBO emailAccessorBO, OrderSplitHelper orderSplitHelper,
            boolean shouldSplit) {
        this.size = size;
        this.ticker = ticker;
        this.ibAccessorBO = ibAccessorBO;
        this.emailAccessorBO = emailAccessorBO;
        this.orderSplitHelper = orderSplitHelper;
        this.shouldSplit = shouldSplit;
    }

    @Override
    public void run() {
        if (this.shouldSplit) {
            List<Integer> splitSizes = this.orderSplitHelper
                    .splitStkBuyOrder(size);
            Timer timer = new Timer();
            double taskID = 0;
            for (int splitSize : splitSizes) {
                STKBuyOrderTask stkBuyOrderTask = new STKBuyOrderTask(
                        splitSize, ticker, ibAccessorBO, emailAccessorBO,
                        orderSplitHelper, false);
                timer.schedule(stkBuyOrderTask, (long) (taskID * 1000));
                taskID += 0.5;
            }
            TimerKillerTask timerKillerTask = new TimerKillerTask(timer);
            timer.schedule(timerKillerTask, (long) (taskID * 1000));
        } else {
            this.ibAccessorBO.createSTKMktBuyOrder(ticker, size);
            this.emailAccessorBO.sendNewStockBuyOrderEmail(ticker, size + "");
        }
    }

}
